package com.xdf.whiteaccount.service.impl;

import com.xdf.whiteaccount.entity.*;
import com.xdf.whiteaccount.enums.BillTypeDyeGrey;
import com.xdf.whiteaccount.exception.BusinessException;
import com.xdf.whiteaccount.service.*;
import com.xdf.whiteaccount.utils.Example;
import com.xdf.whiteaccount.utils.SystemTypeConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class BillDyeGreyServiceImpl implements BillDyeGreyService {
    @Autowired
    private SystemTypeConverter systemTypeConverter;
    @Autowired
    private DyeGreyMainService mainService;
    @Autowired
    private DyeGreyDetailService detailService;
    @Autowired
    private JrkbillsumService jrkbillsumService;// 白坯打卷数据，前端传递来的主键是该表主键
    @Lazy
    @Autowired
    private BillDyeGreyServiceImpl meService;
    @Autowired
    private BillDyeGreyServiceChecker checker;

    @Transactional
    @Override
    public List<BillDyeGrey> insert(List<Integer> jrkbillsumIdList){
        List<DyeGreyDetail> dyeGreyDetailList = detailService.get8JrkbillsumPK(jrkbillsumIdList);
        List<String> distClientList = jrkbillsumService.getDistClient8PrimaryKeyList(jrkbillsumIdList);

        if(distClientList == null || distClientList.size() == 0) throw new BusinessException("传入的白坯汇总主键没有对应数据，无法生成发货单！");
        if(dyeGreyDetailList == null || dyeGreyDetailList.size() == 0) throw new BusinessException("白坯打卷汇总表中没有相关数据！");

        List<Integer> mainIdList = new ArrayList<>();
        // 每个客户生成一个发货单
        for (String s : distClientList) {
            // 创建主表
            DyeGreyMain main = mainService.getNew8ClientSid(s, BillTypeDyeGrey.TRANS_SELF);
            main = mainService.insertSelective(main);
            Integer mainId = Optional.ofNullable(main.getId()).orElse(0);
            mainIdList.add(mainId);

            // 获取当前客户的所有打卷汇总数据
            List<DyeGreyDetail> detailList = dyeGreyDetailList.stream().filter(item -> item.getClient().equalsIgnoreCase(s)).collect(Collectors.toList());
            for (DyeGreyDetail dyeGreyDetail : detailList) {
                dyeGreyDetail.setParentId(mainId);
                detailService.insertSelective(dyeGreyDetail);
            }
        }

        // 获取新增的多个单据并返回
        ArrayList<BillDyeGrey> billDyeGreyArrayList = new ArrayList<>();
        for (Integer id : mainIdList) {
            BillDyeGrey billDyeGrey = meService.selectByPrimaryKey(id);
            billDyeGreyArrayList.add(billDyeGrey);
        }
        return billDyeGreyArrayList;
    }

    @Transactional
    @Override
    public BillDyeGrey insert(BillDyeGrey record) throws Exception {
        checker.isEmpty(record);

        DyeGreyMain main = record.getMain();
        List<DyeGreyDetail> detailList = record.getDetailList();

        main = mainService.insertSelective(main);
        Integer mainId = Optional.ofNullable(main.getId()).orElse(0);
        for (DyeGreyDetail item : detailList) {
            item.setParentId(mainId);
            detailService.insertSelective(item);
        }

        return meService.selectByPrimaryKey(mainId);
    }

    /**
     * 明细数据根据是否有主键决定修改还是新增
     * @param record
     * @return
     */
    @Transactional
    @Override
    public BillDyeGrey update(BillDyeGrey record) {
        DyeGreyMain main = record.getMain();
        List<DyeGreyDetail> detailList = record.getDetailList();
        if(main == null) throw new BusinessException("空数据无法保存！");

        Integer mainId = Optional.ofNullable(main.getId()).orElse(0);
        mainService.updateByPrimaryKeySelective(main);

        if(detailList != null && detailList.size() > 0)
        for (DyeGreyDetail detailItem : detailList) {
            Integer id = Optional.ofNullable(detailItem.getId()).orElse(0);
            if(id.equals(0)){
                detailItem.setParentId(mainId);
                detailService.insertSelective(detailItem);
            }else{
                detailService.updateByPrimaryKeySelective(detailItem);
            }
        }

        return meService.selectByPrimaryKey(mainId);
    }

    @Transactional
    @Override
    public int delete(Integer mainId) {
        Example example = new Example().andEq("parent_id", mainId);
        List<DyeGreyDetail> list = detailService.selectByExample(example);
        if(list !=null && list.size() > 0)
            for (DyeGreyDetail item : list) {
                detailService.deleteByPrimaryKey(item.getId());
            }
        mainService.deleteByPrimaryKey(mainId);
        return 1;
    }

    @Transactional
    @Override
    public BillDyeGrey selectByPrimaryKey(Integer mainId) {
        DyeGreyMain main = mainService.selectByPrimaryKey(mainId);
        BillDyeGrey billDyeGrey = new BillDyeGrey();
        billDyeGrey.setMain(main);

        Example example = new Example().andEq("parent_id", mainId);
        List<DyeGreyDetail> list = detailService.selectByExample(example);
        billDyeGrey.setDetailList(list);
        return billDyeGrey;
    }

    @Override
    public List<BillDyeGrey> selectAll() {
        List<DyeGreyMain> dyeGreyMains = mainService.selectAll();
        if(dyeGreyMains == null || dyeGreyMains.size() == 0) return null;

        ArrayList<BillDyeGrey> retList = new ArrayList<>();
        for (DyeGreyMain item : dyeGreyMains) {
            BillDyeGrey billDyeGrey = meService.selectByPrimaryKey(item.getId());
            retList.add(billDyeGrey);
        }
        return retList;
    }

    @Transactional
    @Override
    public BillDyeGrey insert(BillDyeGrey4Jrkbillsum record) throws Exception{
        DyeGreyMain main = record.getMain();
        List<Integer> jrkbillsumIdList = record.getJrkbillsumIdList();
        if(main == null) throw new BusinessException("发货单主表数据不可为空！");
        if(jrkbillsumIdList == null || jrkbillsumIdList.size() == 0) throw new BusinessException("明细数据不可为空！");

        main = mainService.insertSelective(main);
        Integer mainId = Optional.ofNullable(main.getId()).orElse(0);
        for (Integer jrkbillsumId : jrkbillsumIdList) {
            Jrkbillsum jrkbillsum = jrkbillsumService.selectByPrimaryKey(jrkbillsumId);
            DyeGreyDetail dyeGreyDetail = systemTypeConverter.jrkbillsum2DyeGreyDetail(jrkbillsum);
            dyeGreyDetail.setParentId(mainId);
            detailService.insertSelective(dyeGreyDetail);
        }

        return meService.selectByPrimaryKey(mainId);
    }
}
